﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using app_plugin_api;   //插件接口API

//Destoon网站发帖插件
namespace app_plugin_cechina_cn
{
    /// <summary>
    /// Destoon网站发帖插件
    /// </summary>
    public class cechina : Form, IPluginAPI
    {
        /// <summary>
        /// 构造函数,加载Xml文件和登录网站
        /// </summary>
        public cechina()
        {
            web.ScriptErrorsSuppressed = true;            

            LoadXmlConfig();        //加载xml文件
            LoadLoginPage();        //登录网站

            this.TopMost = true;
            web.Dock = DockStyle.Fill;
            this.Controls.Add(web);
            this.Show();
        }
        
        /// <summary>
        /// 加载Xml配置文件
        /// </summary>
        private void LoadXmlConfig()
        {
            try
            {
                xmlDoc = new XmlDocument();
                string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugin\\");
                if (!Directory.Exists(filePath)) return;

                filePath += this.GetType().Module.Name + ".xml";
                xmlDoc.Load(filePath);

                //初始化根节点
                root = xmlDoc.DocumentElement;
            }
            catch { }
        }

        /// <summary>
        /// 加载登录页面
        /// </summary>
        private void LoadLoginPage()
        {
            if (root.ChildNodes.Count != 0)
            {
                //获取根(root)节点下第(index)个子节点属性(home)的值(value)；即Url地址。
                string home = root.ChildNodes.Item(index).Attributes["home"].Value;     //第1个默认登录地址                                
                web.Url = new Uri(home);
                web.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(web_DocumentCompleted);
            }
        }

        /// <summary>
        /// 加载发布文章页面
        /// </summary>
        private void LoadAddNews()
        {
            if (root.ChildNodes.Count != 0 && root.ChildNodes.Count >= 2)
            {
                //获取根(root)节点下第(index)个子节点属性(home)的值(value)；即Url地址。
                //string home = root.ChildNodes.Item(index).Attributes["home"].Value;     //第2个默认发帖地址
                //web.Url = new Uri(home);
                //web.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(web_DocumentCompleted);
            }
        }

        /// <summary>
        /// 实现接口发送一条新闻
        /// </summary>
        /// <param name="news">新闻数据结构</param>
        /// <returns>返回消息</returns>
        public string SendNews(News news)
        {
            this.news = news;
            
            //导航到添加文章页面
            //LoadAddNews();

            //Post方式
            string referer = "http://home.cechina.cn/blog/post.aspx";
            string heads = "Content-Type:application/x-www-form-urlencoded\nReferer:" + referer;
            string post = string.Format("ctl00$ctl00$ctl00$cpMainWrapper$cpBaseMain$cpRightMain$txtTitle={0}&ctl00$ctl00$ctl00$cpMainWrapper$cpBaseMain$cpRightMain$ddlSystemCategory=10104&ctl00$ctl00$ctl00$cpMainWrapper$cpBaseMain$cpRightMain$txtEditor={1}&ctl00$ctl00$ctl00$cpMainWrapper$cpBaseMain$cpRightMain$txtLabel=&ctl00$ctl00$ctl00$cpMainWrapper$cpBaseMain$cpRightMain$cbEnableReply=on&ctl00$ctl00$ctl00$cpMainWrapper$cpBaseMain$cpRightMain$Button1=发布日志", news.Title, news.Content);
            byte[] byteDate = Encoding.GetEncoding(web.Document.Encoding).GetBytes(post);
            web.Navigate(referer, "_self", byteDate, heads);

            return "请求已被处理";
        }

        //登录网站 和 发布新闻操作
        private void web_DocumentCompleted(object send, WebBrowserDocumentCompletedEventArgs e)
        {
            if (web.ReadyState == WebBrowserReadyState.Complete)
            {
                /*
                 * 操作步骤：
                 * 0.登录
                 * 1.发帖
                 */

                switch (index)
                {
                    case 0:
                        {
                            int runNumber = InitializeDocument(index);
                            if (runNumber == 0) index++;
                            break;
                        }
                    case 1:
                        {
                            InitializeDocument(index);
                            break;
                        }
                }
            }
        }

        /// <summary>
        /// 根据制定Xml文件节点遍历文档
        /// </summary>
        /// <param name="n">节点编号</param>
        /// <returns>0操作成功 1操作失败</returns>
        private int InitializeDocument(int n)
        {
            HtmlDocument loginDoc = web.Document;
            XmlNodeList nodeItem = root.ChildNodes[n].ChildNodes;

            for (int i = 0; i < nodeItem.Count; i++)
            {
                string node_id = nodeItem[i].Attributes["id"].Value;        //id属性
                string node_name = nodeItem[i].Attributes["name"].Value;    //name属性
                string node_value = nodeItem[i].Attributes["value"].Value;  //value属性
                string node_type = nodeItem[i].Attributes["type"].Value;    //元素类型

                for (int j = 0; j < loginDoc.All.Count; j++)    //登录页面元素遍历
                {
                    if (node_id == loginDoc.All[j].Id && node_name == loginDoc.All[j].Name)
                    {
                        if (node_type == "submit" && loginDoc.All[j].GetAttribute("type") == "submit")
                        {
                            web.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(web_DocumentCompleted);
                            loginDoc.All[j].InvokeMember("click");  //执行登录                                          
                            return 0;   //操作成功
                        }
                        else
                        {
                            //0自动登录模式 1发文章模式
                            if (n == 0)
                            {
                                loginDoc.All[j].InnerText = node_value;  //元素赋值
                            }
                            else
                            {
                                switch (node_value)
                                {
                                    case "title":
                                        loginDoc.All[j].SetAttribute("value", news.Title);
                                        break;
                                    case "content":
                                        loginDoc.All[j].SetAttribute("value", news.Content);
                                        break;
                                }
                            }
                        }
                    }
                }
            }
            return 1;   //操作失败
        }

        /// <summary>
        /// Xml文档
        /// </summary>
        private XmlDocument xmlDoc;
        /// <summary>
        /// xml文章根节点
        /// </summary>
        private XmlElement root;
        /// <summary>
        /// WebBrowse对象
        /// </summary>
        private WebBrowser web = new WebBrowser();
        /// <summary>
        /// 新闻数据结构
        /// </summary>
        private News news;
        /// <summary>
        /// Xml节点索引
        /// </summary>
        private int index = 0;
    }
}